﻿using System.IO;
using System.Text.RegularExpressions;

namespace Neoit.Utils.TemplateParser
{
    /// <summary>
    /// parse eg: <part $="Layout/Header.html"/>
    /// </summary>
    public class ParsePart
    {
        public const string tagPattern = @"<part\s+\$='(.*?)'\s*/>";
        public static string Parse<T>(string template, T data, string templateFilePath)
        {
            if (string.IsNullOrEmpty(template) || data == null) return template;
            var matches = Regex.Matches(template, tagPattern);

            foreach (Match match in matches)
            {
                var filePath = match.Groups[1].Value;
                var partContent = string.Empty;
                if (!Regex.IsMatch(filePath, @"^\w:"))
                {
                    filePath = $"{Path.GetFullPath(Path.Combine(Path.GetDirectoryName(templateFilePath), filePath))}";
                }
                partContent = File.ReadAllText(filePath);
                template = Regex.Replace(template, tagPattern, partContent);
            }
            return template;
        }
    }
}
